Swagger剛開始可以將其理解成網頁版本的postman
我們可以對其測試發送資料看回傳結果
在預設webapi專案產生的WeatherForecastController
新增一個post action
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyNet5ApiAdoTest.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
[HttpPost("Add")]
public string AddWeatherForecast(WeatherForecast weather)
{
if(weather != null)
{
DateTime dt = weather.Date;
string summary = weather.Summary;
int TemperatureC = weather.TemperatureC;
int TemperatureF = weather.TemperatureF;
return "1";
}
return "0";
}
}
}
在此準備一份json 測試資料嘗試post
{
"date":"2022-06-09T09:49:03.3956842+08:00",
"temperatureC":9,
"temperatureF":47,
"summary":"Hot"
}
在專案中下中斷點
下方則會呈現回應結果與curl對應呼叫語法轉譯
而在Swagger中若我們想自訂API文檔給其他外部開發者或廠商去做使用
移至我們的Startup.cs的ConfigureServices方法
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerDocument(config => {
config.PostProcess = document =>
{
//API版號
document.Info.Version = "v1.0.1";
//API名稱
document.Info.Title = "廠房MES API 測試";
//API描述介紹
document.Info.Description = "提供原物料資料查詢存取";
//API聯絡人資訊
document.Info.Contact = new NSwag.OpenApiContact
{
Name = "XXX科技",
Email = "ppap@outlook.com",
Url = "https://#"
};
//API授權許可資訊
document.Info.License = new NSwag.OpenApiLicense
{
Name = "XXX科技 版權所有",
Url = "https://#"
};
};
});//註冊NSwag提供的服務
}
而一般API官方文件也會習慣寫中英文的註解描述各隻API功能
在C#專案我們都知道可透過XML在每個函數、method上方添加功能描述註解
若寫好的API這樣子呈現別人會不曉得功能與目的
由於預設專案是不會開啟產生XML註解並讀取機制的
因此要自己去開啟
本篇已同步發表至個人部落格
https://coolmandiary.blogspot.com/2022/01/net-core-web-api22swagger.html